/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ScrollView,
  Dimensions,
  Image,
  TouchableOpacity,
  ListView,
  DeviceEventEmitter,
  NativeAppEventEmitter,
  Platform,
  BackAndroid,
  Alert,
  ActivityIndicator,
  Modal,
  AsyncStorage
} from 'react-native';

import Header from "./Component/Header";
import  Swiper from 'react-native-swiper';
var deviceWidth = Dimensions.get('window').width;

import Icon from 'react-native-vector-icons/FontAwesome';
import SideMenu from 'react-native-side-menu';
import BleManager from 'react-native-ble-manager';

var SQLite = require('react-native-sqlite-storage');

var base64 = require('base64-js');
var _navigator;
var listdata1 = [];
var blestatus;

var db;
var user_id;
var _this;

class TabDevice extends Component {
	constructor(props) {
        super(props);
        
        _navigator = this.props.navigator;
        
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        
        this.state = {
        	dataSource1: ds,
			modalVisible:false,
			sideopen:false,
			models:false,
			blescan:false,
        };
        
        db = SQLite.openDatabase({name : "idolly.db", createFromLocation : 1}, this.successCB, this.errorCB);
//      db.transaction((tx) => {
//		  tx.executeSql('create TABLE t_device(id VARCHAR NOT NULL, name VARCHAR NOT NULL);', [], (tx, results) => {
//		      console.log("Query completed");
//		
//		
//		      var len = results.rows.length;
//		      for (let i = 0; i < len; i++) {
//		        let row = results.rows.item(i);
//		        console.log(`Employee name: ${row.name}, Dept Name: ${row.deptName}`);
//		      }
//		    });
//		});
		AsyncStorage.getItem("user_id",function(errors,result){
			console.log(result);
			user_id = result;
			if(result != null){
				console.log('SELECT * FROM t_device where user_id like "'+user_id+'"');
				db.transaction((tx) => {
					tx.executeSql('SELECT * FROM t_device where user_id like "'+user_id+'"', [], (tx, results) => {
						
						DeviceEventEmitter.emit('updateDevice',results);
					});
				});
			}
		});
		
		BleManager.checkState();
    }
	
	updateDevice(results){
		console.log("Query completed");
						
		console.log(results);
		var len = results.rows.length;
		console.log(len);
		for (let i = 0; i < len; i++) {
			let row = results.rows.item(i);
			var obj = {name:row.name,id:row.mac};
			console.log(obj);
			listdata1.push(obj);
		}
		this.setState({dataSource1: this.state.dataSource1.cloneWithRows(listdata1)});	
	}
	
	errorCB(err) {
		console.log("SQL Error: " + err);
	}
	 
	successCB() {
		console.log("SQL executed fine");
	}
	 
	openCB() {
		console.log("Database OPENED");
	}
	
	openSideMenu(){
		this.setState({sideopen:true});
	}
	
	
    Menu(){
    	return(
    		<Text>123</Text>
    	);
    }
    
    componentWillUnmount(){
      	NativeAppEventEmitter
          	.removeListener('BleManagerDidUpdateState', this.checkblestatus );
      
      	NativeAppEventEmitter
      			.removeListener('BleManagerDidUpdateValueForCharacteristic',this.DidUpdateValueForCharacteristic);
      			
      	NativeAppEventEmitter
          	.removeListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral );
          	
		DeviceEventEmitter.removeListener('disconnect',this.disconnect);
		
      	DeviceEventEmitter
      			.removeListener('writeData',this.blewrite);
      			
      	NativeAppEventEmitter
			.removeListener('BleManagerStopScan',this.handleStopScan);
		
		NativeAppEventEmitter
			.removeListener('updateDevice',this.updateDevice);
			
      	listdata1 = [];
	    this.subscription.remove();
		this.disconnect();
	}
				
	componentDidMount() {
		//ble相关监听函数
		this.updateDevice = this.updateDevice.bind(this);
        NativeAppEventEmitter
			.addListener('updateDevice',this.updateDevice);
        
        this.checkblestatus = this.checkblestatus.bind(this);
        this.handleDiscoverPeripheral = this.handleDiscoverPeripheral.bind(this);
        
        NativeAppEventEmitter
           .addListener('BleManagerDidUpdateState', this.checkblestatus);
      
      	this.DidUpdateValueForCharacteristic = this.DidUpdateValueForCharacteristic.bind(this);
      	NativeAppEventEmitter
      		.addListener('BleManagerDidUpdateValueForCharacteristic',this.DidUpdateValueForCharacteristic);
      	
      	this.handleDiscoverPeripheral = this.handleDiscoverPeripheral.bind(this);
      	NativeAppEventEmitter
           .addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral );
        
        this.handleStopScan = this.handleStopScan.bind(this);
        NativeAppEventEmitter
			.addListener('BleManagerStopScan',this.handleStopScan);
			
      	this.refreshAAvatar = this.refreshAAvatar.bind(this);
      	this.blewrite = this.blewrite.bind(this);
      	this.disconnect = this.disconnect.bind(this); 
	    this.subscription = DeviceEventEmitter.addListener('changeAvatar',this.refreshAAvatar);
		DeviceEventEmitter.addListener('writeData',this.blewrite);
		DeviceEventEmitter.addListener('disconnect',this.disconnect);
		
		
		
		this._setModalVisible = this._setModalVisible.bind(this);
    }
	
	_setModalVisible(status){
		this.setState({models:false});
		BleManager.stopScan().then(() => {
		    // Success code
		    console.log('Scan stopped');
		});
	}

	refreshAAvatar(data){
		listdata1.push(data);
		console.log(data.id.toString());
		var dd = 'SELECT * FROM t_device where user_id like "'+user_id+'"';
		db.transaction((tx) => {
		  	tx.executeSql('SELECT * FROM t_device where user_id like "'+user_id+'"', [], (tx, results) => {
		      	console.log(results);
		      	var len = results.rows.length;
		      	
				for (let i = 0; i < len; i++) {
				    let row = results.rows.item(i);
				    if(data.id === row.mac){
				    	Alert.alert("请勿重复添加");
				    	return;
				    }
				}
		      	
				db.transaction((tx) => {
				tx.executeSql('INSERT INTO t_device(name,mac,user_id) VALUES(?, ?, ?)', [data.name,data.id,user_id], (tx, results) => {
				    console.log("Query completed");
					});
				});
					
			    this.setState({dataSource1: this.state.dataSource1.cloneWithRows(listdata1)});  
		    });
		});	
		
	}
	
	handleDiscoverPeripheral(data){
        console.log('Got ble data', data);
       
       	if(data.id == this.state.connectid)
        {
			BleManager.stopScan();
        	this.setState({bleID:this.state.connectid});
        }
   }
		
	handleStopScan(data){
		if(!this.state.blescan)
			return;
		
		this.setState({blescan:false});
		if(this.state.models == false){
			return;
		}
		BleManager.connect(this.state.connectid).then(() => {		
			if(this.state.devicename.substr(0,4) === 'Kbra'){
				_navigator.push({id:"ControlPage",title:"智能按摩Kbra系列胸罩",mode:0,bleid:this.state.bleID});
			}else if(this.state.devicename.substr(0,6) === 'IDOLLY'){
				_navigator.push({id:"ControlPage",title:"智能按摩Idolly系列胸罩",mode:1,bleid:this.state.bleID});
			}
			this.setState({models:false});
		}).catch((error) => {				
			BleManager.connect(this.state.connectid).then(() => {	
				if(this.state.devicename.substr(0,4) === 'Kbra'){
					_navigator.push({id:"ControlPage",title:"智能按摩Kbra系列胸罩",mode:0,bleid:this.state.bleID});
				}else if(this.state.devicename.substr(0,6) === 'IDOLLY'){
					_navigator.push({id:"ControlPage",title:"智能按摩Idolly系列胸罩",mode:1,bleid:this.state.bleID});
				}
				this.setState({models:false});
			}).catch((error) => {				
				Alert.alert("提示","连接失败,请重新连接");
				this.setState({models:false});
				console.log(error);
			});
			console.log(error);
		});
	}
		
	DidUpdateValueForCharacteristic(data){
		console.log('Got ble data', data);
				
	}
		
	checkblestatus(data){
 		console.log(data.state);
 		if(data.state == "off"){
 			Alert.alert("请手动打开蓝牙");
 		}
    }
	
	stringToBytes(str) {  
		var ch, st, re = [];  
		for (var i = 0; i < str.length; i++ ) {  
		    ch = str.charCodeAt(i);  // get char   
		    st = [];                 // set up "stack"  
		    do {  
		      st.push( ch & 0xFF );  // push byte to stack  
		      ch = ch >> 8;          // shift value down by 1 byte  
		    }    
		    while ( ch );  
		    // add stack contents to result  
		    // done because chars have "wrong" endianness  
		    re = re.concat( st.reverse() );  
		}  
		  // return an array of bytes  
		return re;  
	}  
		
	blewrite(data){
			 // Success code 
		if(data.name === 'Kbra'){
			
			var sedata = base64.fromByteArray(data.cmd);
			
     		BleManager
     			.write(this.state.bleID, '00001523-1212-efde-1523-785feabcd123', '00001524-1212-efde-1523-785feabcd123', sedata).then(() => {
					console.log("success");
				})
				.catch((error) => {
					console.log(error);
			}); 
		}else if(data.name === 'IDOLLY'){
			var sedata = base64.fromByteArray(this.stringToBytes(data.cmd));	
			console.log(sedata);
			BleManager
     			.write(this.state.bleID, '0000ffb0-0000-1000-8000-00805f9b34fb', '0000ffb2-0000-1000-8000-00805f9b34fb', sedata).then(() => {
					console.log("success");
				})
				.catch((error) => {
					console.log(error);
			}); 
		}
	}
		
	_netback(data){
		console.log(data);
	}
		
	disconnect(flag){
		BleManager.disconnect(this.state.bleID).then(() => {
			
			console.log("disconnect");
		}).catch((error) => { 
			// Failure code 
			console.log(error);
		});
	}
	
	connectble(id){
		console.log(id);
		this.setState({connectid:id})
		BleManager.scan([], 5, true)
	            .then((results) => {console.log('Scanning...'); });
	}
	
	_pressRow(rowData){
		//Alert.alert(rowData.id);
		this.setState({models:true,blescan:true,devicename:rowData.name});
		this.connectble(rowData.id);
		//_navigator.push({id: "ControlPage",title:"智能按摩内衣"});
	}
	
	_longpressRow(rowID,rowData){
		Alert.alert(
            '提醒',
            '是否删除此设备',
            [
              	{text: '取消', onPress: () => console.log('OK Pressed!')},
              	{text: '确定',onPress:()=>{
              		console.log(listdata1);
              		var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
					listdata1.splice(rowID,1);
					console.log(listdata1);
					this.setState({dataSource1: ds.cloneWithRows(listdata1)});
					db.transaction((tx) => {
					  	tx.executeSql('delete from t_device where mac like "'+rowData.id+'"', [], (tx, results) => {
					      	console.log("delete success");
					    });
					});	
              	}}
            ]
        );
	}
            
    _renderRow(rowData, sectionID, rowID){
        return (
        	<TouchableOpacity onPress={()=>this._pressRow(rowData)} onLongPress={()=>this._longpressRow(rowID,rowData)}>
			    <View style={styles.devices}>
			      	<Image source={require('./image/devices/bra.png')} style={{width:80,height:80,marginLeft:20}}/>
			      	<View style={{marginLeft:20,justifyContent: 'center',}}>
			      		<Text style={{fontSize:14}}>{rowData.name}</Text>
			      		<Text style={{fontSize:10,color:'#aaaaaa'}}>未连接</Text>
			      	</View>
			    </View>
		    </TouchableOpacity>
        );
    }
    
 	render() {
 		const menu = this.Menu();
 		
	    return (
		    <View style={styles.container}>
		      	<Header name="设备列表" IconRight="plus" onPressRight={()=> _navigator.push({id:"DeviceList"})}/>
		      	<ListView 
		      	 	enableEmptySections = {true}
		      		dataSource={this.state.dataSource1}
		      		renderRow={this._renderRow.bind(this)}/>
		      	<Modal
				animationType={this.state.animationType}
				transparent={true}
				visible={this.state.models}
				onRequestClose={() => this._setModalVisible(false)}
				>
					<View style={styles.centering}>
			      	<ActivityIndicator
				        animating={this.state.animating}
				        style={[styles.centering, {height: 80}]}
				        size="large"
				   	/>
			      	<Text>正在连接</Text>
			      	</View>
				</Modal>
		    </View>
	    );
  	}
}

const styles = StyleSheet.create({
	header: {
		height:80
	},
	centering: {
		width:Dimensions.get('window').width,
		height:Dimensions.get('window').height,
	    alignItems: 'center',
	    justifyContent: 'center',
	    padding: 8,
	},
	container: {
	    flex: 1,
	    backgroundColor: '#FAF4FF',
	},
	welcome: {
	    fontSize: 20,
	    textAlign: 'center',
	    margin: 10,
	},
	instructions: {
	    textAlign: 'center',
	    color: '#333333',
	    marginBottom: 5,
	},
	headerbar:{
		flexDirection:'row',
	  	height: 80,
	  	width: Dimensions.get('window').width,
	},
	headIcon:{
		width:60,
  		height:80,
  		marginLeft:10,
  		justifyContent: 'center',
	},
	headName:{
		width:60,
  		height:80,
  		justifyContent: 'center',
	},
	logo:{
  		width:50,
  		height:50
 	},
  	mainbar:{
  		flex:1,
  		marginTop:10
  	},
  	image:{
  		width:Dimensions.get('window').width
  	},  
  	wrapper: {
  	},
  	slide: {
    	flex: 1,
    	justifyContent: 'center',
    	backgroundColor: 'transparent'
  	},
  	slide1: {
    	flex: 1,
    	justifyContent: 'center',
    	alignItems: 'center',
    	backgroundColor: '#9DD6EB'
  	},
  	slide2: {
    	flex: 1,
    	justifyContent: 'center',
    	alignItems: 'center',
    	backgroundColor: '#97CAE5'
  	},
  	slide3: {
    	flex: 1,
    	justifyContent: 'center',
    	alignItems: 'center',
    	backgroundColor: '#92BBD9'
  	},
    scrollview: {  
	    flex: 1,  
	    marginBottom:30,
	   	borderWidth:1,
	   	width:Dimensions.get('window').width,
	    borderColor:"#000000"
	},
  	devices:{
  		width:Dimensions.get('window').width-20,
  		marginLeft:10,
  		height:130,
  		borderBottomWidth:1,
		borderBottomColor:"#A2B5CD",
    	alignItems: 'center',
    	flexDirection:'row',
  	},
});


module.exports = TabDevice;
